package com.example.countscore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class currencyExchange extends AppCompatActivity implements Runnable{

    public static final String TAG = "currencyExchange";

    float dollar_rate = 0.1547f;
    float euro_rate = 0.1320f;
    float won_rate = 182.4343f;
    Handler handler;
    TextView resText;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_exchange);

        resText = findViewById(R.id.welcomeText);

        //使用SharedPreferences对象接受当前汇率数据
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);

        dollar_rate = sharedPreferences.getFloat("dollar_rate_key2", 0.0f);
        euro_rate = sharedPreferences.getFloat("euro_rate_key2", 0.0f);
        won_rate = sharedPreferences.getFloat("won_rate_key2", 0.0f);

        Log.i(TAG, "currencyOnCreate: dollar_rate=" + dollar_rate);
        Log.i(TAG, "currencyOnCreate: euro_rate=" + euro_rate);
        Log.i(TAG, "currencyOnCreate: won_rate=" + won_rate);

        //获取SharedPreferences对象中记录的时间，若未存储过该数据，取出则为""
        String updateDateStr = sharedPreferences.getString("update_date","");
        //获取当前系统时间
        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todaystr = sdf.format(today);

        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG, "handleMessage: 收到消息");
                if(msg.what==6){

                    if(updateDateStr.equals("")){
                        //更新数据---接收消息
                        Bundle bdl = (Bundle) msg.obj;
                        dollar_rate = bdl.getFloat("key_dollar");
                        euro_rate = bdl.getFloat("key_euro");
                        won_rate = bdl.getFloat("key_won");

                        Toast.makeText(currencyExchange.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "handleMessage: bdl=" + bdl.getFloat("key_dollar"));

                    }
                    else{
                        //将String转为Date
                        Date updateDate = null;
                        try {
                            updateDate = sdf.parse(updateDateStr);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        //计算两个时间差值
                        long diff = today.getTime()-updateDate.getTime();
                        long day = diff/(1000*24*60*60);
                        Log.i(TAG, "onCreate: 相差天数day：" + day);

                        //更新——已过去1天
                        if(day>0){
                            //接收消息
                            Bundle bdl = (Bundle) msg.obj;
                            dollar_rate = bdl.getFloat("key_dollar");
                            euro_rate = bdl.getFloat("key_euro");
                            won_rate = bdl.getFloat("key_won");

                            Toast.makeText(currencyExchange.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                            Log.i(TAG, "handleMessage: bdl=" + bdl.getFloat("key_dollar"));
                        }
                    }

                    //更新SharedPreferences当中存储时间
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("update_date", todaystr);
                    editor.apply();
                }
                super.handleMessage(msg);
            }
        };
        //启动线程
        MyTask task = new MyTask();
        task.setHandler(handler);
        Thread thread = new Thread(task);
        thread.start(); //this.run()
    }

    //计算汇率转化
    public void clickCurrency(View btn) {

        Log.i(TAG, "click1");

        //获取当前用户输入RMB
        EditText rmb = findViewById(R.id.inputRMB);
        String rmb_temp = rmb.getText().toString();
        Log.i(TAG, "click: rmb="+rmb_temp);

        //获取转换后位置数据
//        TextView resText = findViewById(R.id.welcomeText);
        if(rmb_temp.equals("")){
            //用户尚未输入，报错提示
            Toast.makeText(this, "请输入需要换算的人民币数值", Toast.LENGTH_SHORT).show();
            resText.setText(R.string.welcome);
        }
        else{
            float rmb_num = Float.valueOf(rmb_temp);

            if(btn.getId()==R.id.Dollar){
                rmb_num *= dollar_rate;
            }else if(btn.getId()==R.id.Euro){
                rmb_num *= euro_rate;
            }else if(btn.getId()==R.id.Won){
                rmb_num *= won_rate;
            }
            Log.i(TAG, "click: res="+rmb_num);

            //返回汇率换算后结果
            resText.setText(String.valueOf(rmb_num));
        }

    }

    //打开新页面，发送当前汇率值
    public void clickConfig(View v){
        Log.i(TAG, "open: config");
        openConfig();

    }

    private void openConfig() {
        //打开新窗口
        Intent config = new Intent(this, com.example.countscore.config.class);
        config.putExtra("dollar_rate_key", dollar_rate);
        config.putExtra("euro_rate_key", euro_rate);
        config.putExtra("won_rate_key", won_rate);

        Log.i(TAG, "clickConfig: dollarRate=" + dollar_rate);
        Log.i(TAG, "clickConfig: euroRate=" + euro_rate);
        Log.i(TAG, "clickConfig: wonRate=" + won_rate);

//        startActivity(config);
        startActivityForResult(config, 1);
    }

    //接收save传值结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //requestCode是哪个窗口带回来的, resultCode表明窗口带回来的哪个数据
        if(requestCode==1 && resultCode==3){
            //不打包方式带回数据
            dollar_rate = data.getFloatExtra("dollar_rate_key2", 0.1547f);
            euro_rate = data.getFloatExtra("euro_rate_key2", 0.1320f);
            won_rate = data.getFloatExtra("won_rate_key2", 182.4343f);

            Log.i(TAG, "onActivityResult: dollar_rate=" + dollar_rate);
            Log.i(TAG, "onActivityResult: euro_rate=" + euro_rate);
            Log.i(TAG, "onActivityResult: won_rate=" + won_rate);
        }else if(requestCode==1 && resultCode==5){
            //打包方式带回数据
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    //menu菜单项
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate, menu);
        return true;
    }

    //选中菜单项
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.menu_set){
            //打开新窗口
            openConfig();
        }

        return super.onOptionsItemSelected(item);
    }

    //将输入流InputStream转换为String
    private String inputStream2String(InputStream inputStream) throws IOException{

        final int bufferSize=1024;
        final char[] buffer= new char[bufferSize];
        final StringBuilder out= new StringBuilder();
        Reader in= new InputStreamReader(inputStream,"gb2312");
        while (true){
            int rsz = in.read(buffer, 0, buffer.length);
            if(rsz < 0)
                break;
            out.append(buffer, 0 ,rsz);
        }
        return out.toString();
    }

    @Override
    public void run(){
        Log.i(TAG, "run: 111");
//        try {
//            Thread.sleep(3000);//延迟
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        //获取网络数据
//        URL url =null;
//        try{
//            url = new URL("http://www.usd-cny.com/icbc.htm");
//            HttpURLConnection http = (HttpURLConnection)url.openConnection();
//            InputStream in = http.getInputStream();
//
//            String html = inputStream2String(in);
//            Log.i(TAG, "run: html=" + html);
//
//        }catch (MalformedURLException e){
//            e.printStackTrace();
//        }catch (IOException e){
//            e.printStackTrace();
//        }

        //使用Jsoup
        try {
            Document doc = Jsoup.connect("https://usd-cny.com/").get();
            Element firstTable = doc.getElementsByTag("table").first();
            Elements trs = firstTable.getElementsByTag("tr");
            trs.remove(0); //删除表头

            //初始化Bundle，存储计算所得汇率
            Bundle bdl = new Bundle();
            for(Element tr:trs){
                Elements tds = tr.getElementsByTag("td");
                Element td1 = tds.get(0);
                Element td2 = tds.get(4);

                if("美元".equals(td1.text())){
                    float rate = 100f / Float.parseFloat(td2.text());
                    Log.i(TAG, "run: td1="+td1.text()+"----->rate="+rate);
                    bdl.putFloat("key_dollar",rate);
                }
                if("欧元".equals(td1.text())){
                    float rate = 100f / Float.parseFloat(td2.text());
                    Log.i(TAG, "run: td1="+td1.text()+"----->rate="+rate);
                    bdl.putFloat("key_euro",rate);
                }
                if("韩币".equals(td1.text())){
                    float rate = 100f / Float.parseFloat(td2.text());
                    Log.i(TAG, "run: td1="+td1.text()+"----->rate="+rate);
                    bdl.putFloat("key_won",rate);
                }

                //发送消息
                Message msg = handler.obtainMessage(6);
                msg.obj = bdl;
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}